home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9760 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: garden.csc.calpoly.edu!not-for-mail
  2. From: dstubbs@garden.csc.calpoly.edu (Dan Stubbs)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: while loop problem
  5. Date: 12 Mar 1996 16:58:44 -0800
  6. Organization: Cal Poly, San Luis Obispo
  7. Message-ID: <4i56k4$n5d@garden.csc.calpoly.edu>
  8. References: <Pine.OSF.3.91.960312133449.7844B-100000@io.UWinnipeg.ca> <Do6DB0.EtE@microunity.com>
  9. NNTP-Posting-User: dstubbs@garden.csc.calpoly.edu
  10.  
  11. In article <Do6DB0.EtE@microunity.com>,
  12. Tom Sanders <toms@MicroUnity.com> wrote:
  13. >In article <Pine.OSF.3.91.960312133449.7844B-100000@io.UWinnipeg.ca>, Bill Simpson <wsimpson@uwinnipeg.ca> writes:
  14. >|> Consider the following code fragment:
  15. >|> 
  16. >|> y=2000; z=1000;
  17. >|> x=0;
  18. >|> while(x<=XMAX)
  19. >|>     {
  20. >|>     x+=(int) erand(mean);
  21. >|>     setdot(x,y,z);
  22. >|>     }
  23. >|>     
  24. >|> The above code will also attempt to plot one point at an x value >XMAX
  25. >|> before it terminates.
  26. >|> Is there a nice way to write the code so it works properly?
  27. >|> 
  28. >|> The only way I have thought of is
  29. >|> y=2000; z=1000;
  30. >|> x=0;
  31. >|> while(x<=XMAX)
  32. >|>     {
  33. >|>     x+=(int) erand(mean);
  34. >|>     if(x<=XMAX)
  35. >|>         setdot(x,y,z);
  36. >|>     }
  37. >|> 
  38. >|> which seems very clumsy since the same test is done twice.
  39. >|> 
  40.  
  41. There are several basic ways to do it. All of them rely on
  42. computing the first value to plot *before* entering the loop.
  43. That is, essentially operating like a for loop. In your loop
  44. x is initialized to 0 and then the 0 is discarded without being
  45. used. Starting with the first value to plot allows you to
  46. reverse the innards of the loop and avoid the extra test.
  47.  
  48.     y=2000; z=1000;
  49.     x = (int) erand(mean); 
  50.     while(x<=XMAX) 
  51.         {
  52.         setdot(x,y,z);
  53.         x+=(int) erand(mean);
  54.         }
  55.  
  56. or
  57.  
  58.     y=2000; z=1000;
  59.     x = (int) erand(mean);
  60.     for (; x<=XMAX; x = (int) erand(mean))
  61.        setdot(x,y,z);
  62.  
  63. or (a bit clumsy)
  64.  
  65.     y=2000; z=1000;
  66.     x = (int) erand(mean);
  67.     if (x <= XMAX)
  68.        do {
  69.             setdot(x,y,z);
  70.             x+=(int) erand(mean);
  71.          } while (x <= XMAX)
  72.  
  73.